package com.bjpowernode.controller;

import com.bjpowernode.beans.Stu;
import com.bjpowernode.dto.ResultDTO;
import com.bjpowernode.validation.StuValidation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Locale;

@RestController
@RequestMapping("/")
public class IndexController {


    @Autowired
    MessageSource messageSource;


    @RequestMapping("get.action")
    public ResultDTO get(Stu stu, BindingResult bindingResult) {
        StuValidation stuValidation = new StuValidation();
        stuValidation.validate(stu, bindingResult);
        if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                System.out.println("字段名：" + fieldError.getField());
                System.out.println("错误code：" + fieldError.getCode());
                System.out.println("错误RejectedValue：" + fieldError.getRejectedValue());
                System.out.println("错误DefaultMessage：" + fieldError.getDefaultMessage());
                String code = fieldError.getCode();
                String message = messageSource.getMessage(code, null, Locale.getDefault());
                System.out.println("外部自定义的message：" + message);
            }
        }

        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setResult(ResultDTO.SUCCESS);
        resultDTO.setData(stu);
        return resultDTO;
    }
}
